package com.system.Service.Impl;

import com.common.Constant.Constants;
import com.common.Utils.JwtUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.system.Entity.GuestBook;
import com.system.Entity.ReplyLog;
import com.system.Mapper.GuestBookMapper;
import com.system.Service.EmailService;
import com.system.Service.GuestBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class GuestBookServiceImpl implements GuestBookService {

    @Autowired
    private GuestBookMapper guestBookMapper;
    @Autowired
    private EmailService mailService;

    @Override
    public void addGB(GuestBook guestBook) {
        guestBook.setGbId(String.valueOf(System.currentTimeMillis()));
        guestBook.setStatus("0");
        guestBook.setGbTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        guestBookMapper.addGB(guestBook);
    }

    @Override
    public PageInfo<GuestBook> getList(Integer pageNum, Integer pageSize, String status) {
        PageHelper.startPage(pageNum,pageSize);
        List<GuestBook> list = guestBookMapper.getList(status);
        return new PageInfo<>(list);
    }

    @Override
    public void deleteGB(String gbId) {
        guestBookMapper.deleteGB(gbId);

        guestBookMapper.deleteReply(gbId);

    }

    @Override
    public void reply(ReplyLog replyLog) {
        //设置回复人员用户名
        String token = replyLog.getToken();
        String user= JwtUtil.extractUsername(token);
        replyLog.setReplyUser(user);

        //回复内容发送给留言人邮箱
        String subject = Constants.ReplySubject;
        String email = replyLog.getEmail();
        //发送邮件
        mailService.sendSimpleMail(email,subject,replyLog.getReplyContent());

        //设置回复时间
        replyLog.setReplyTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));

        replyLog.setReplyId(getId());
        guestBookMapper.reply(replyLog);
        guestBookMapper.updateStatus(replyLog.getGbId());

    }

    @Override
    public  List<ReplyLog> replyHistory(String gbId) {
        return guestBookMapper.replyHistory(gbId);

    }

    private String getId(){
        String id = UUID.randomUUID().toString();
        return "R"+id;
    }


}
